<!-- The exported code uses Tailwind CSS. Install Tailwind CSS in your dev environment to ensure all styles work. -->

<template>
  <div class="p-6">
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-800">安全设置</h1>
      <p class="text-gray-500 mt-2">管理您的账户安全信息，保护账户安全</p>
    </div>

    <!-- 密码管理卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">密码管理</h2>
          <p class="text-sm text-gray-500 mt-1">定期更改密码可以提高账户安全性</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Lock /></el-icon>
      </div>

      <div class="flex items-center mb-4">
        <div class="flex-1">
          <div class="text-sm text-gray-600 mb-2">密码强度</div>
          <div class="flex items-center">
            <div :class="passwordStrengthBars[0]" class="h-2 rounded-full w-24"></div>
            <div :class="passwordStrengthBars[1]" class="h-2 rounded-full w-24 ml-1"></div>
            <div :class="passwordStrengthBars[2]" class="h-2 rounded-full w-24 ml-1"></div>
            <div :class="passwordStrengthBars[3]" class="h-2 rounded-full w-24 ml-1"></div>
            <span class="ml-3 text-sm" :class="passwordStrengthColor">{{ passwordStrengthText }}</span>
          </div>
        </div>
        <div>
          <button
            @click="showPasswordDialog = true"
            class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors cursor-pointer whitespace-nowrap !rounded-button"
          >
            修改密码
          </button>
        </div>
      </div>

      <div class="text-xs text-gray-500">上次修改时间：2025-04-10 10:23:45</div>
    </div>

    <!-- 手机绑定卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">手机绑定</h2>
          <p class="text-sm text-gray-500 mt-1">绑定手机可用于登录、找回密码和接收安全通知</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Phone /></el-icon>
      </div>

      <div class="flex items-center">
        <div class="flex-1">
          <div class="text-sm text-gray-600 mb-2">已绑定手机</div>
          <div class="text-lg font-medium text-gray-800">{{ userInfo?.phoneNumber || '未绑定' }}</div>
        </div>
      </div>
    </div>

    <!-- 邮箱绑定卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">邮箱绑定</h2>
          <p class="text-sm text-gray-500 mt-1">绑定邮箱可用于登录、找回密码和接收安全通知</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Message /></el-icon>
      </div>

      <div class="flex items-center">
        <div class="flex-1">
          <div class="text-sm text-gray-600 mb-2">已绑定邮箱</div>
          <div class="text-lg font-medium text-gray-800">{{ userInfo?.email || '未绑定' }}</div>
        </div>
      </div>
    </div>

    <!-- 登录历史记录卡片 -->
    <div class="bg-white rounded-lg shadow p-6 mb-6">
      <div class="flex items-center justify-between mb-4">
        <div>
          <h2 class="text-lg font-medium text-gray-800">登录历史记录</h2>
          <p class="text-sm text-gray-500 mt-1">查看近期的登录记录，发现异常及时处理</p>
        </div>
        <el-icon class="text-blue-500 text-2xl"><Clock /></el-icon>
      </div>

      <!-- 加载状态 -->
      <div v-if="loginHistoryLoading" class="flex justify-center items-center py-8">
        <el-icon class="animate-spin text-blue-500 text-2xl mr-2"><Loading /></el-icon>
        <span class="text-gray-500">加载中...</span>
      </div>

      <!-- 登录记录表格 -->
      <div v-else class="mb-4">
        <div class="flex items-center justify-between mb-2 pb-2 border-b border-gray-100">
          <div class="text-sm font-medium text-gray-600">登录时间</div>
          <div class="text-sm font-medium text-gray-600">登录地点</div>
          <div class="text-sm font-medium text-gray-600">登录设备</div>
          <div class="text-sm font-medium text-gray-600">登录状态</div>
        </div>

        <div
          v-for="(record, index) in loginHistory"
          :key="index"
          class="flex items-center justify-between py-3 border-b border-gray-100"
        >
          <div class="text-sm text-gray-600">{{ formatTime(record.loginTime) }}</div>
          <div class="text-sm text-gray-600">{{ record.loginLocation || '未知' }}</div>
          <div class="text-sm text-gray-600">{{ getDeviceDisplayName(record.loginDevice) }}</div>
          <div>
            <el-tag :type="record.loginStatus === 1 ? 'success' : 'danger'" size="small">
              {{ record.loginStatus === 1 ? '成功' : '失败' }}
            </el-tag>
          </div>
        </div>

        <!-- 无数据状态 -->
        <div v-if="loginHistory.length === 0" class="flex flex-col items-center justify-center py-12">
          <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
            <el-icon class="text-gray-400 text-2xl">
              <Clock />
            </el-icon>
          </div>
          <h3 class="text-lg font-medium text-gray-700 mb-2">暂无登录记录</h3>
          <p class="text-gray-500 text-center">
            还没有登录记录数据
          </p>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="!loginHistoryLoading && totalLoginRecords > 0" class="flex justify-between items-center">
        <div class="text-sm text-gray-500">共 {{ totalLoginRecords }} 条记录</div>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="totalLoginRecords"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <div v-else-if="!loginHistoryLoading" class="text-right">
        <button
          @click="loadLoginHistory"
          class="px-4 py-2 text-blue-500 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors cursor-pointer whitespace-nowrap !rounded-button"
        >
          <el-icon class="mr-1.5">
            <Refresh />
          </el-icon>
          重新加载
        </button>
      </div>
    </div>

    <div class="bg-yellow-50 rounded-lg p-4 border border-yellow-200 mb-6">
      <div class="flex items-start">
        <el-icon class="text-yellow-500 mt-1"><WarningFilled /></el-icon>
        <div class="ml-3">
          <h3 class="text-sm font-medium text-yellow-800">安全提示</h3>
          <p class="text-xs text-yellow-700 mt-1">
            为了保障您的账户安全，请勿将账户信息泄露给他人，定期更换密码，不要在不信任的设备上登录账户。
            如发现账户异常，请立即修改密码并联系客服。
          </p>
        </div>
      </div>
    </div>

    <!-- 密码修改弹框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="500px"
      :close-on-click-modal="false"
      center
    >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="80px"
        class="password-form"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="passwordForm.email"
            placeholder="请输入您的邮箱地址"
            :disabled="passwordForm.emailConfirmed"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="verificationCode">
          <div class="verification-input-group">
            <el-input
              v-model="passwordForm.verificationCode"
              placeholder="邮箱验证码"
              :disabled="!passwordForm.email"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <el-button
              type="primary"
              :loading="sendCodeLoading"
              :disabled="!passwordForm.email || sendCodeDisabled"
              @click="handleSendCode"
              size="default"
              style="margin-left: 10px;"
            >
              {{ sendCodeText }}
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPasswordChange">取消</el-button>
          <el-button
            type="primary"
            :loading="passwordChangeLoading"
            @click="handlePasswordChange"
            :disabled="!isPasswordFormValid"
          >
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import {
  User,
  Lock,
  Bell,
  ChatDotRound,
  Picture,
  VideoPlay,
  Medal,
  Star,
  ShoppingCart,
  List,
  Document,
  Upload,
  Phone,
  Message,
  Clock,
  WarningFilled,
  Laptop,
  Mobile,
  Desktop,
  Loading,
  Refresh,
  Key,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter1 } from '../utils/useRoute'
import { getUserInfo, clearUserInfo } from '@/utils/auth'
import { getUserLoginRecords, LoginRecord, LoginDevice, sendUpdateVerificationCode, updatePassword } from '@/api/user'
import { useRouter } from 'vue-router'

const router = useRouter()
const {
  goToHome,
  goToDocumentUpload,
  goToKnowledgeBaseManagement,
  goToMemberCenter,
  goToNotificationSettings,
  goToOrder,
  goToPointsManagement,
  goToSecuritySettings,
  goToUser,
  goToAiChat,
  goToAiDrawing,
  goToProduct,
} = useRouter1()

// 用户信息
const userInfo = getUserInfo()

// 登录历史记录相关
const loginHistory = ref([])
const loginHistoryLoading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalLoginRecords = ref(0)

// 密码修改弹框相关
const showPasswordDialog = ref(false)
const passwordFormRef = ref()
const passwordChangeLoading = ref(false)
const sendCodeLoading = ref(false)
const sendCodeDisabled = ref(false)
const sendCodeText = ref('发送验证码')
const countDown = ref(0)

// 密码修改表单
const passwordForm = ref({
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: '',
  phoneNumber: userInfo?.phoneNumber || '', // 从用户信息中获取手机号
  emailConfirmed: false
})

// 密码修改表单验证规则
const passwordRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为6位', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
}

// 判断密码修改表单是否有效
const isPasswordFormValid = computed(() => {
  const form = passwordForm.value
  return (
    form.email &&
    form.verificationCode &&
    form.newPassword &&
    form.confirmPassword &&
    form.newPassword === form.confirmPassword
  )
})

// 时间格式化函数
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取设备显示名称
const getDeviceDisplayName = (device) => {
  if (!device) return '未知设备'
  
  const { operatingSystem, browser, deviceType } = device
  let displayName = ''
  
  if (operatingSystem) {
    displayName += operatingSystem
  }
  
  if (browser) {
    displayName += (displayName ? ' / ' : '') + browser
  }
  
  if (deviceType && !displayName.includes(deviceType)) {
    displayName += (displayName ? ' / ' : '') + deviceType
  }
  
  return displayName || '未知设备'
}

// 加载登录历史记录
const loadLoginHistory = async () => {
  loginHistoryLoading.value = true
  try {
    const response = await getUserLoginRecords({
      page: {
        page: currentPage.value,
        limit: pageSize.value,
        order: 'DESC',
        field: 'login_time'
      }
    })
    
    loginHistory.value = response.data || []
    totalLoginRecords.value = response.totalCount || 0
  } catch (error) {
    console.error('获取登录历史记录失败:', error)
    ElMessage.error('获取登录历史记录失败')
  } finally {
    loginHistoryLoading.value = false
  }
}

// 分页处理
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  loadLoginHistory()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  loadLoginHistory()
}

// 密码强度计算
const passwordStrength = computed(() => {
  const complexity = userInfo?.passwordComplexity
  
  // 根据强度等级返回对应的样式和文本
  // null=最低，1=强，2=中，3=低
  if (complexity === null || complexity === undefined) {
    return {
      bars: ['bg-red-500', 'bg-gray-200', 'bg-gray-200', 'bg-gray-200'],
      text: '最低',
      color: 'text-red-600'
    }
  }
  
  switch (complexity) {
    case 1:
      return {
        bars: ['bg-green-500', 'bg-green-500', 'bg-green-500', 'bg-green-500'],
        text: '强',
        color: 'text-green-600'
      }
    case 2:
      return {
        bars: ['bg-yellow-500', 'bg-yellow-500', 'bg-yellow-500', 'bg-gray-200'],
        text: '中',
        color: 'text-yellow-600'
      }
    case 3:
      return {
        bars: ['bg-orange-500', 'bg-orange-500', 'bg-gray-200', 'bg-gray-200'],
        text: '低',
        color: 'text-orange-600'
      }
    default:
      return {
        bars: ['bg-gray-200', 'bg-gray-200', 'bg-gray-200', 'bg-gray-200'],
        text: '未知',
        color: 'text-gray-600'
      }
  }
})

const passwordStrengthBars = computed(() => passwordStrength.value.bars)
const passwordStrengthText = computed(() => passwordStrength.value.text)
const passwordStrengthColor = computed(() => passwordStrength.value.color)

// 处理发送验证码
const handleSendCode = async () => {
  if (!passwordForm.value.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(passwordForm.value.email)) {
    ElMessage.warning('请输入正确的邮箱格式')
    return
  }

  try {
    sendCodeLoading.value = true
    
    await sendUpdateVerificationCode({ email: passwordForm.value.email })
    
    ElMessage.success('验证码已发送，请查收邮箱')
    
    // 开始倒计时
    startCountDown()
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败，请稍后再试')
  } finally {
    sendCodeLoading.value = false
  }
}

// 开始倒计时
const startCountDown = () => {
  countDown.value = 60
  sendCodeDisabled.value = true
  
  const timer = setInterval(() => {
    countDown.value--
    sendCodeText.value = `${countDown.value}s后重发`
    
    if (countDown.value <= 0) {
      clearInterval(timer)
      sendCodeDisabled.value = false
      sendCodeText.value = '发送验证码'
    }
  }, 1000)
}

// 处理密码修改
const handlePasswordChange = async () => {
  if (!passwordFormRef.value) return

  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        passwordChangeLoading.value = true

        // 准备修改参数
        const { confirmPassword, emailConfirmed, ...changeParams } = passwordForm.value

        // 调用密码修改API
        await updatePassword(changeParams)

        ElMessage.success('密码修改成功，请使用新密码重新登录')

        // 清空本地用户信息缓存
        clearUserInfo()

        // 关闭弹框
        showPasswordDialog.value = false

        // 跳转到登录页面
        router.push('/login')
      } catch (error) {
        ElMessage.error(error.message || '密码修改失败，请稍后再试')
      } finally {
        passwordChangeLoading.value = false
      }
    }
  })
}

// 取消密码修改
const cancelPasswordChange = () => {
  showPasswordDialog.value = false
  // 重置表单
  passwordForm.value = {
    email: '',
    verificationCode: '',
    newPassword: '',
    confirmPassword: '',
    phoneNumber: userInfo?.phoneNumber || '',
    emailConfirmed: false
  }
  // 重置验证码状态
  sendCodeDisabled.value = false
  sendCodeText.value = '发送验证码'
  countDown.value = 0
  // 清除表单验证
  if (passwordFormRef.value) {
    passwordFormRef.value.resetFields()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadLoginHistory()
})
</script>

<style scoped>
:deep(.el-icon) {
  font-size: 1.25rem;
}

input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 密码修改弹框样式 */
.password-form .el-form-item {
  margin-bottom: 20px;
}

.verification-input-group {
  display: flex;
  align-items: center;
  width: 100%;
}

.verification-input-group .el-input {
  flex: 1;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
